package com.uenpay.im.ui.old.activity.wallet;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.socks.library.KLog;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.alipay.AliPayParameters;
import com.uenpay.im.ui.old.activity.alipay.ExternalPartner;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.service.bean.BankCardInfo;
import com.uenpay.service.model.IBankCardModel;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.net.listener.HttpOnNextListener;

import java.util.List;

/**
 * @author SL
 * @created 2016-1-14 18:58:22
 * @copyRight http://www.qiyunxin.com
 * @function 充值
 */
public class ChargeActivity extends BaseActivity {

    private EditText amout_et;
    private Button next_btn;
    private PayBroadCastReceiver mPayBroadCastReceiver;

    private IBankCardModel mBankCardModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_charge_layout;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        Utils.showSoftKeyboard(amout_et);
        mBankCardModel = (IBankCardModel) ARouter.getInstance().build("/service/backcard").navigation();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.red_recharge));
        next_btn = (Button) findViewById(R.id.next_btn);
        amout_et = (EditText) findViewById(R.id.amout_et);
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Utils.hideSoftKeyboard(amout_et);
                        finish();
                    }
                });
        amout_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                String str = arg0.toString();
                if (!TextUtils.isEmpty(str)) {
                    setMoney(str);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        next_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String amount = amout_et.getText().toString();
                if (!TextUtils.isEmpty(amount)) {
                    double temp = Double.valueOf(amount);
                    if (temp > 5000) {
                        IMApplication.showToast(R.string.charge_max);
                    } else {
                        //              recharge(amount);
                        checkPayType(amount, "99");
                    }
                } else {
                    IMApplication.showToast(R.string.input_charge);
                }
            }
        });
    }

    private void recharge(String amount) {
        WalletHandle.charge(amount, new WalletHandle.IChargeListener() {

            @Override
            public void onChargeResult(
                    ChargeInvokItem.ChargeInvokItemResult mChargeInvokItemResult) {
                if (mChargeInvokItemResult != null) {
                    if (mChargeInvokItemResult.status == HttpInvokeResultCode.RESULT_OK) {

                        Intent intent = new Intent(ChargeActivity.this, ExternalPartner.class);
                        intent.putExtra(AliPayParameters.SIGN, mChargeInvokItemResult.sign);
                        intent.putExtra(AliPayParameters.CHARSET, mChargeInvokItemResult.charset);
                        intent.putExtra(AliPayParameters.METHOD, mChargeInvokItemResult.method);
                        intent.putExtra(AliPayParameters.APP_ID, mChargeInvokItemResult.app_id);
                        intent.putExtra(AliPayParameters.SIGN_TYPE, mChargeInvokItemResult.sign_type);
                        intent.putExtra(AliPayParameters.TIMESTAMP, mChargeInvokItemResult.timestamp);
                        intent.putExtra(AliPayParameters.VERSION, mChargeInvokItemResult.version);
                        intent.putExtra(AliPayParameters.NOTIFY_URL, mChargeInvokItemResult.notify_url);
                        intent.putExtra(AliPayParameters.BIZ_CONTENT, mChargeInvokItemResult.biz_content);
                        startActivity(intent);
                    } else if (!TextUtils.isEmpty(mChargeInvokItemResult.msg)) {
                        IMApplication.showToast(mChargeInvokItemResult.msg);
                    }
                }
            }
        });
    }

    private void checkPayType(final String amount, final String payType) {
        if ("99".equals(payType)) {
            mBankCardModel.getUserBankList(new HttpOnNextListener<List<BankCardInfo>>() {
                @Override
                public void onNext(List<BankCardInfo> bankCardInfos) {
                    if (bankCardInfos != null && bankCardInfos.size() > 0) {
                        KLog.d("checkPayType result: " + bankCardInfos.get(0).toString());
                        recharge(amount, payType, bankCardInfos.get(0).getUserBankId() + "");
                    } else {
                        Toasts.shortToast(ChargeActivity.this, "请先绑定银行卡！");
                    }
                }
            });
        }
    }

    private void recharge(String amount, String payType, String memo) {

        WalletHandle.chargeByCard(amount, memo, new WalletHandle.IChargeByCardListener() {
            @Override
            public void onChargeResult(ChargeByCardInvokItem.ChargeByCardInvokItemResult mChargeByCardInvokItemResult) {
                if (mChargeByCardInvokItemResult != null) {
                    if (mChargeByCardInvokItemResult.status == HttpInvokeResultCode.RESULT_OK) {
                        KLog.d("recharge result:" + mChargeByCardInvokItemResult.rspCode + " " + mChargeByCardInvokItemResult.tradeNo + " " + mChargeByCardInvokItemResult.resMsg);
                        if (!TextUtils.isEmpty(mChargeByCardInvokItemResult.tradeNo) && !TextUtils.isEmpty(mChargeByCardInvokItemResult.wkPayNo)) {
                            ARouter.getInstance().build("/test/test").withString("tradeNo", mChargeByCardInvokItemResult.tradeNo)
                                    .withString("wkPayNo", mChargeByCardInvokItemResult.wkPayNo)
                                    .navigation(ChargeActivity.this);
                        }
                    } else if (!TextUtils.isEmpty(mChargeByCardInvokItemResult.msg)) {
                        IMApplication.showToast(mChargeByCardInvokItemResult.msg);
                    }
                }
            }
        });
    }

    private void setMoney(String s) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = (String) s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                amout_et.setText(s);
                amout_et.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            amout_et.setText(s);
            amout_et.setSelection(2);
        }

        if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                amout_et.setText(s.subSequence(0, 1));
                amout_et.setSelection(1);
                return;
            }
        }
    }

    public class PayBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (arg1.getAction().equals(BroadcastAction.PAY_ASSISTANT_ACTION)) {
                ChargeActivity.this.setResult(RESULT_OK);
                Utils.hideSoftKeyboard(amout_et);
                finish();
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPayBroadCastReceiver == null) {
            mPayBroadCastReceiver = new PayBroadCastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(BroadcastAction.PAY_ASSISTANT_ACTION);
            registerReceiver(mPayBroadCastReceiver, filter);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IMApplication.getInstance().removeActivity(this);
        if (mPayBroadCastReceiver != null) {
            unregisterReceiver(mPayBroadCastReceiver);
        }
    }
}
